package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shop1/models"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	var err error

	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "账号密码不能为空",
		}
		c.ServeJSON()
		return
	}

	users := models.User{
		Username: username,
		Password: password,
	}

	if err = users.GetUsernameByUser(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "系统错误",
		}
		c.ServeJSON()
		return
	}
	if users.ID > 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "用户已存在",
		}
		c.ServeJSON()
		return
	}
	if err = users.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "创建失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": "注册成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) Login() {
	var err error

	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "账号密码不能为空",
		}
		c.ServeJSON()
		return
	}

	users := models.User{
		Username: username,
		Password: password,
	}

	if err = users.GetUsernameByUser(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "系统错误",
		}
		c.ServeJSON()
		return
	}
	if users.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "用户不存在",
		}
		c.ServeJSON()
		return
	}
	if users.Password != password {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": "注册成功",
	}
	c.ServeJSON()
	return
}
